package com.hyg.lib_music.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_music.R;
import com.hyg.lib_music.adapter.MusicPlayListAdapter;
import com.hyg.lib_music.databinding.ActivityPlayingListBinding;
import com.hyg.lib_music.modle.CategoryMusicListData;
import com.hyg.lib_music.modle.RecommedMusicData;
import com.hyg.lib_music.service.MusicService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PlayingListActivity extends BaseActivity {

    ActivityPlayingListBinding binding;
    ArrayList<RecommedMusicData.DataDTO> getData;
    ArrayList<Music> list;
    String title = "";
    boolean isEditing = false;
    MusicPlayListAdapter mAdapter;
    int type, sleepMusicType, parentType;
    String test_result;
    ArrayList<RecommedMusicData.DataDTO> dtoArrayList;
    boolean needRefresh=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPlayingListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
    }


    public void init() {
        initData();
        binding.viewMusicPlayController.setMenuVisiable(View.INVISIBLE);
//        initTitleView();
    }

    private void initData() {
        StatusBarUtil.setTranslucent(this, 0);
        list = new ArrayList<>();
        list = getIntent().getParcelableArrayListExtra("data");
        Music currentMusic = MusicMainActivity.serviceBinder.getCurrentMusic();
        if (currentMusic != null && MusicMainActivity.serviceBinder.isPlaying()) {
            for (Music music : list) {
                if (music.musicName.equals(currentMusic.musicName)) {
                    music.isPlaying = true;
                }else{
                    music.isPlaying = false;
                }
            }
        } else {
            for (Music music : list) {
                music.isPlaying = false;
            }
        }
        initRecyclerView(list);
        initTitleView(list);
        initPlayerStateChangeListener();
    }


    public void initPlayerStateChangeListener(){
        MusicMainActivity.serviceBinder.registerOnStateChangeListener(listenr);
    }

    //实现监听器监听MusicService的变化，
    private MusicService.OnStateChangeListenr listenr = new MusicService.OnStateChangeListenr() {
        @Override
        public void onPlayProgressChange(long played, long duration) {

        }

        @Override
        public void onPlay(final Music item) {
            Log.i("lgb", "onPlay: ");
            for(Music music:list){
                music.isPlaying=false;
                if(music.musicName.equals(item.musicName)){
                    music.isPlaying=true;
                }
            }
            if(mAdapter!=null){
                mAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onPause() {
            //变为暂停状态时

        }
    };



    private void initRecyclerView(ArrayList<Music> list) {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        binding.rcvPlayingList.setLayoutManager(layoutManager);
        mAdapter = new MusicPlayListAdapter(this, list);
        binding.rcvPlayingList.setAdapter(mAdapter);
    }

    private void initTitleView(ArrayList<Music> list) {
        binding.lnTitleView.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        switch (list.get(list.size() - 1).parentType) {
            case 1:
                title = "养生定制方案";
                binding.lnTitleView.tvTitleMore.setVisibility(View.VISIBLE);
                break;
            case 2:
                title = "助眠定制方案";
                binding.lnTitleView.tvTitleMore.setVisibility(View.VISIBLE);
                break;
            case 3:
                title = "解压定制方案";
                binding.lnTitleView.tvTitleMore.setVisibility(View.VISIBLE);
                break;
            default:
                title = "播放列表";
                binding.lnTitleView.tvTitleMore.setVisibility(View.GONE);
                break;
        }

        parentType = list.get(list.size() - 1).parentType;
        sleepMusicType = list.get(list.size() - 1).sleepMusicType;
        test_result = list.get(list.size() - 1).testResult;

        binding.lnTitleView.tvTitle.setText(title);
        binding.lnTitleView.back.setImageResource(R.mipmap.back_white);
        binding.lnTitleView.tvTitle.setTextColor(getResources().getColor(R.color.white));
        binding.lnTitleView.tvTitleMore.setTextColor(getResources().getColor(R.color.white));
        binding.lnTitleView.tvTitleMore.setText("编辑");
        binding.lnTitleView.tvTitleMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                titleViewOnclick();
            }
        });

        binding.cbSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                for (Music dataDTO : list) {
                    dataDTO.isChecked = isChecked;
                }
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

        binding.lnChangeMusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lnChangeMusicOnclick();
            }
        });

        binding.lnAddFav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lnAddMusicFavOnclick();
            }
        });
        binding.lnPlayAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicMainActivity.serviceBinder.addPlayList(list, list.get(0));
            }
        });
    }

    private void titleViewOnclick() {
        if (isEditing) {
            binding.lnPlayAll.setVisibility(View.VISIBLE);
            binding.lnSelectAll.setVisibility(View.GONE);
            binding.lnTitleView.tvTitleMore.setText("编辑");
            binding.lnTitleView.tvTitle.setText(title);
            binding.lnBottomEdit.setVisibility(View.GONE);
            isEditing = false;
            for (Music music : list) {
                music.isEditable = false;
            }
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
        } else {
            binding.lnTitleView.tvTitleMore.setText("完成");
            binding.lnTitleView.tvTitle.setText("编辑乐单");
            isEditing = true;
            binding.lnPlayAll.setVisibility(View.GONE);
            binding.lnSelectAll.setVisibility(View.VISIBLE);
            binding.lnBottomEdit.setVisibility(View.VISIBLE);
            for (Music music : list) {
                music.isEditable = true;
            }
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    private void lnChangeMusicOnclick() {
        ArrayList<String> id_list = new ArrayList<>();
        for (Music dataDTO : list) {
            if (dataDTO.isChecked) {
                id_list.add(dataDTO.id + "");
            }
        }

        if (id_list.size() > 0) {
            CommonHttpUtil.changeHealthMusic(PlayingListActivity.this, id_list, type, sleepMusicType, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Toast.makeText(PlayingListActivity.this, "连接服务器失败！", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    Log.i("lgb", "onResponse: "+result);
                    parseChangeMusicReceiveData(result);
                }
            });
        }
    }

    public void parseChangeMusicReceiveData(String data) {
        dtoArrayList = new ArrayList<>();
        RecommedMusicData musicData = JSONObject.parseObject(data, RecommedMusicData.class);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (musicData.getCode() == 200) {
                    dtoArrayList = (ArrayList<RecommedMusicData.DataDTO>) musicData.getData();
                    list.clear();
                    for (RecommedMusicData.DataDTO dataDTO : dtoArrayList) {
                        new Music(dataDTO.getId(), dataDTO.getMusicName(), dataDTO.getMusician(), dataDTO.getMusicDuration(),
                                dataDTO.getRegion(), dataDTO.getMusicUrl(), (dataDTO.getFavorite() == 1),
                                parentType, sleepMusicType, test_result,
                                (MusicMainActivity.serviceBinder.isPlaying() && MusicMainActivity.serviceBinder.getCurrentMusic().musicName.equals(dataDTO.musicName)),
                                true, false);
                    }
                    if (mAdapter != null) {
                        mAdapter.notifyDataSetChanged();
                    }
                } else {
                    ErrorDialog(musicData.getMessage());
                }
            }
        });
    }


    private void lnAddMusicFavOnclick() {
        ArrayList<Integer> id_list = new ArrayList<>();
        for (Music dataDTO : list) {
            if (dataDTO.isChecked) {
                id_list.add(dataDTO.id);
            }
        }
        if (id_list.size() > 0) {
            CommonHttpUtil.addMultilFavList(PlayingListActivity.this, id_list.toString(), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Toast.makeText(PlayingListActivity.this, "连接服务器失败！", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    Log.i("lgb", "onResponse:ssdad222 " + result);
                    for(int id:id_list){
                        EventBus.getDefault().post(new EventBusMessage(Constants.Add_Favorite,id));
                    }
                }
            });
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(needRefresh && mAdapter!=null){
            mAdapter.notifyDataSetChanged();
        }
    }

    @Subscribe
    public void onEvent(EventBusMessage message) {
        //接收以及处理数据
        if (message.getmessage().equals(Constants.Add_Favorite)) {
            for (Music music : list) {
                if (music.id == message.getMusicId()) {
                    music.isFav = true;
                }
            }
            needRefresh = true;
        } else if (message.getmessage().equals(Constants.Cancel_Favorite)) {
            for (Music music : list) {
                if (music.id == message.getMusicId()) {
                    music.isFav = false;
                }
            }
            needRefresh = true;
        }
    }

    @Override
    public void finish() {
        super.finish();
        MusicMainActivity.serviceBinder.unregisterOnStateChangeListener(listenr);
        EventBus.getDefault().unregister(this);
    }
}